package com.zoewin.zephyr.reportjasper.factory.exporter;

import jcifs.util.Base64;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Created by WQL on 2020/8/5
 * CEASE TO STRUGGLE AND YOU CEASE TO LIVE
 */
public class POIWordExporter implements IExporter {

    @Override
    public String getBase64(Object document) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//二进制OutputStream
        try {
            ((XWPFDocument)document).write(baos);
            String base64 = Base64.encode(baos.toByteArray());
            return base64;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("get word base64 failed! reason: "+ e.toString());
        }
    }

    @Override
    public void getOutPutStream(Object document) throws Exception {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        OutputStream os = null;
        response.setContentType("application/msword");
        try {
            os = response.getOutputStream();
            ((XWPFDocument)document).write(os);
        } catch (Exception e) {
            throw new Exception("getOutPutStream failed , reason: "+ e.toString());
        }finally {
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                }
            }
        }
    }

    @Override
    public void getDownLoad(Object document, String downLoadPath) throws Exception {
        File file = new File(downLoadPath);
        try {
            FileOutputStream stream = new FileOutputStream(file);
            ((XWPFDocument)document).write(stream);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("download word failed, reason: "+ e.toString());
        }
    }

    @Override
    public byte[] getByteArr(Object document) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//二进制OutputStream
        try {
            ((XWPFDocument)document).write(baos);
            return baos.toByteArray();//OutputStream写入InputStream二进制流
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("get word byte[] failed! reason: "+ e.toString());
        }
    }
}
